/**
 * 安全奖励申请 编辑页
 *
 * 作者 wanghjw
 * 日期 2024-09-03 14:08:36
 */
layui.use(['jquery','febs', 'form', 'validate','autocomplete','table','commonJS','util', 'fileUpload'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        autocomplete = layui.autocomplete,
        fileUpload = layui.fileUpload,
        $view = $('#incentiveRewardApply-edit'),
        $addClauseBtn = $view.find("#addClauseBtn"),
        $addGoods = $view.find("#addGoods"),
        $addUser = $view.find("#addUser"),
        validate = layui.validate,
        tableIns,
        tableIns1;

    let useScope='3';

    var fileUploadDiv = fileUpload.render({
        elem: '#fileUpload',
        url: ctx + 'incentive/upload',
        type: 2,//0-图片，1-视频，2-其他
        maxNum:5,
        defaultData: incentiveRewardApplyData && incentiveRewardApplyData.fileList ? incentiveRewardApplyData.fileList:[],
        done: function (res) {
        },
    });


    form.verify(validate);
    form.render();
    initFormValue();





    function initFormValue() {
        if (incentiveRewardApplyData) {
            form.val("incentiveRewardApply-edit-form", {
                "rewardApplyId": incentiveRewardApplyData.rewardApplyId,
                "tenantId": incentiveRewardApplyData.tenantId,
                "rewardType": incentiveRewardApplyData.rewardType,
                "rewardReason": incentiveRewardApplyData.rewardReason,
                "rewardClauseId": incentiveRewardApplyData.rewardClauseId,
                "rewardClause": incentiveRewardApplyData.rewardClause,
                "rewardClauseRuleId": incentiveRewardApplyData.rewardClauseRuleId,
                "rewardClauseRule": incentiveRewardApplyData.rewardClauseRule,
                "rewardAmount": incentiveRewardApplyData.rewardAmount,
                "bankName": incentiveRewardApplyData.bankName,
                "bankCode": incentiveRewardApplyData.bankCode,
                "rewardScore": incentiveRewardApplyData.rewardScore,
                "applyUserId": incentiveRewardApplyData.applyUserId,
                "applyUserNo": incentiveRewardApplyData.applyUserNo,
                "applyRealName": incentiveRewardApplyData.applyRealName
            });
            if(incentiveRewardApplyData.rewardAmountFlg == '1'){
                $view.find('input[name="rewardAmount"]').removeAttr('disabled');
                $view.find('input[name="rewardAmount"]').attr("lay-verify","required");
                $view.find('input[name="bankCode"]').removeAttr('disabled');
                $view.find('input[name="bankName"]').removeAttr('disabled');
                $view.find('input[name="rewardAmountFlg"]').attr('checked','true');
                $('#bankInfo').removeClass('febs-hide');
            }
            if(incentiveRewardApplyData.rewardScoreFlg == '1'){
                $view.find('input[name="rewardScore"]').removeAttr('disabled');
                $view.find('input[name="rewardScore"]').attr("lay-verify","required");
                $view.find('input[name="rewardScoreFlg"]').attr('checked','true');
            }
            if(incentiveRewardApplyData.rewardGoodsFlg == '1'){
                $addGoods.removeAttr('disabled');
                $addGoods.removeClass('layui-btn-disabled');
                $view.find('input[name="rewardGoodsFlg"]').attr('checked','true');
            }
            if(!commonJS.isEmpty(incentiveRewardApplyData.userList)){
                // var userList = [];
                incentiveRewardApplyData.userList.forEach((item, index) => {
                    item.uname=item.realName
                });
               initUserTable(incentiveRewardApplyData.userList);
            }
            if(!commonJS.isEmpty(incentiveRewardApplyData.goodsList)){
                initGoodsTable(incentiveRewardApplyData.goodsList);
            }
        }else {
            form.val("incentiveRewardApply-edit-form", {
                "tenantId": POPUP_DATA.tenantId,
            });
            initUserTable([]);
            initGoodsTable([]);
        }
    }

    form.on('submit(incentiveRewardApply-save-form-submit)', function (data) {
        if(data.field.rewardGoodsFlg == 'on' && !checkGoodsTable()){
            febs.alert.warn('请选择要奖励的商品,并填写大于0的数量！');
            return false;
        }
        setSwitchValue(data);
        data.field.userList = getUserTable();
        data.field.status = '1'
        data.field.fileList = getFileData();
        addOrUpdate(data.field);
        return false;
    });

    form.on('submit(incentiveRewardApply-edit-form-submit)', function (data) {
        if(data.field.rewardGoodsFlg == 'on' && !checkGoodsTable()){
            febs.alert.warn('请选择要奖励的商品,并填写大于0的数量！');
            return false;
        }
        setSwitchValue(data);
        data.field.userList = getUserTable();
        data.field.status = '2';
        data.field.fileList = getFileData();
        addOrUpdate(data.field);
        return false;
    });

    function addOrUpdate(data) {
        var msg1 = '保存提示！';
        var msg2 = '是否保存？';
        if(data.status == '2'){
            msg1 = '提交提示！';
            msg2 = '是否提交？';
        }
        febs.modal.confirm(msg1,msg2,function (index){
            if (data.rewardApplyId && data.rewardApplyId.length > 0) {
                febs.postArray(ctx + 'incentiveRewardApply/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('修改成功');
                    $('#febs-incentiveRewardApply').find('#query').trigger('click');
                });
            } else {
                febs.postArray(ctx + 'incentiveRewardApply', data, function () {
                    layer.closeAll();
                    febs.alert.success('新增成功');
                    $('#febs-incentiveRewardApply').find('#query').trigger('click');
                });
            }
        })
    }
    function getTenantId(){
        if(incentiveRewardApplyData){
            return incentiveRewardApplyData.tenantId
        }else {
            return POPUP_DATA.tenantId
        }
    }

    $addClauseBtn.on('click', function () {
        var tableData = table.cache["rewardUserTable"]
        if(commonJS.isEmpty(tableData) || tableData.length == 0){
            febs.alert.success("请先选择被奖励人员！");
            return;
        }
        febs.modal.open('选择奖励条款', 'common/incentiveRewardClause', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['70%', '85%'],
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                console.log('选择违章条款'+JSON.stringify(selectData));
                $view.find('input[name="rewardClause"]').val(selectData.clauseName);
                $view.find('input[name="rewardClauseId"]').val(selectData.clauseId);
                $view.find('input[name="rewardClauseRuleId"]').val(selectData.clauseRuleId);
                $view.find('input[name="rewardClauseRule"]').val(selectData.clauseContent);
                $view.find("#sugAmount").text(selectData.referenceMoney);
                $view.find("#sugScore").text(selectData.examineScore);
                $('#suggest').removeClass('febs-hide');
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            },
            data: {
                useScope:useScope,
                tenantId : getTenantId(),
            }
        });

    });

    /**
     * 判断奖励类型，选人的时候是否多选
     * @returns {boolean}
     */
    function getMultiUser(){
        var rewardType = $view.find('select[name="rewardType"]').find("option:selected").val();
        if(rewardType == '1'){
            return false;
        }else {
            return  true;
        }
    }


    $addUser.on('click', function () {
        febs.modal.open('选择用户', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['90%', '85%'],
            data:{
                tenantId:getTenantId(),
                multiple:getMultiUser(),
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                temp = selectData;
                console.log("获得的人员"+JSON.stringify(temp))
                // debugger

                if(selectData){
                    var tableData = [];
                    if(getMultiUser()){
                        tableData = selectData;
                    }else {
                        tableData.push(selectData)
                    }
                    getUseScope(tableData);
                    initUserTable(tableData);
                    layer.close(index);
                }

            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    /**
     * 获取所选用户用户类型
     * @param data
     * @returns {*|string}
     */
    function getUseScope(data){
        var useScopeList =[];
        for (let i = 0; i < data.length; i++) {
            var user = data[i];
            useScopeList.push(user.userType)
        }
        console.log("去重前"+JSON.stringify(useScopeList))
        var newList = Array.from(new Set(useScopeList));
        console.log("去重后"+JSON.stringify(newList))
        if(newList.length ==1){
            useScope = newList[0];
        }else {
            useScope = '3'
        }
    }

    /**
     * 加载奖励人员表
     * @param data
     */
    function initUserTable(data) {
        console.log('ren'+JSON.stringify(data))
        // debugger
        tableIns = febs.table.init({
            elem: $view.find('table[id="rewardUserTable"]'),
            id: 'rewardUserTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {field: 'userId',title: '用户ID',hide:true},
                {field: 'userNo', title: '工号', width: 250,align:'center'},
                {field: 'uname', title: '姓名', width: 250,align:'center'},
                {field: 'deptId', title: '部门ID', width: 120,hide:true},
                {field: 'deptName', title: '部门名称', width: 250,align:'center'},
                {title: '操作', toolbar: '#rewardUserTable-tool',align:'center',width: 80}
            ]],
            data:data
        });

        form.render()
    }

    table.on('tool(rewardUserTable)', function (obj) {
        var data = obj.data,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除数据', '确定删除所选人员？', function () {
                obj.del();
            });
        }
    });

    /**
     * 金额开关
     */
    form.on('switch(rewardAmountFlg)',function (data) {
        if(this.checked){
            $view.find('input[name="rewardAmount"]').removeAttr('disabled');
            $view.find('input[name="rewardAmount"]').attr("lay-verify","required");
            $view.find('input[name="bankCode"]').removeAttr('disabled');
            $view.find('input[name="bankName"]').removeAttr('disabled');
            $('#bankInfo').removeClass('febs-hide');
        }else {
            $view.find('input[name="rewardAmount"]').val('');
            $view.find('input[name="rewardAmount"]').attr('disabled',true);

            $view.find('input[name="rewardAmount"]').attr("lay-verify", "");
            $view.find('input[name="bankCode"]').val('');
            $view.find('input[name="bankCode"]').attr('disabled',true);
            $view.find('input[name="bankName"]').val('');
            $view.find('input[name="bankName"]').attr('disabled',true);
            $('#bankInfo').addClass('febs-hide');
        }
        form.render()
    });

    /**
     * 分数开关
     */
    form.on('switch(rewardScoreFlg)',function (data) {
        if(this.checked){
            $view.find('input[name="rewardScore"]').removeAttr('disabled');
            $view.find('input[name="rewardScore"]').attr("lay-verify","required");
        }else {
            $view.find('input[name="rewardScore"]').val('');
            $view.find('input[name="rewardScore"]').attr('disabled',true);
            $view.find('input[name="rewardScore"]').attr("lay-verify", "");

        }
        form.render()
    });

    /**
     * 商品开关
     */
    form.on('switch(rewardGoodsFlg)',function (data) {
        if(this.checked){
            $addGoods.removeAttr('disabled');
            $addGoods.removeClass('layui-btn-disabled');
        }else {
            $addGoods.attr('disabled',true);
            $addGoods.addClass('layui-btn-disabled');
            tableIns1.reload({'data':[]});
        }
        form.render()
    });


    /**
     * 添加奖励商品
     */
    $addGoods.on('click', function () {
        febs.modal.open('选择商品', 'common/goods', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['90%', '85%'],
            data:{
                tenantId:getTenantId(),
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                temp = selectData;
                console.log("获得的商品"+JSON.stringify(temp))
                if(selectData){
                    var tableData = [];
                    if(Array.isArray(selectData)){
                        tableData = selectData;
                    }else {
                        tableData.push(selectData)
                    }
                    initGoodsTable(tableData);
                    layer.close(index);
                }

            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    /**
     * 加载奖励商品表
     * @param data
     */
    function initGoodsTable(data) {
        tableIns1 = febs.table.init({
            elem: $view.find('table[id="rewardGoodsTable"]'),
            id: 'rewardGoodsTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {field: 'goodsId',title: '商品ID',hide:true},
                {field: 'goodsName', title: '商品名称', minWidth: 500,align:'center'},
                {field: 'goodsNumber', title: '奖励数量', width: 250,align:'center',edit: 'text'},
                {title: '操作', toolbar: '#rewardGoodsTable-tool',align:'center',width: 80}
            ]],
            data:data
        });

        form.render()
    }

    table.on('tool(rewardGoodsTable)', function (obj) {
        var data = obj.data,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除数据', '确定删除所选商品？', function () {
                obj.del();
            });
        }
    });

    /**
     * 商品表编辑
     */
    table.on('edit(rewardGoodsTable)',function (obj) {
        var value = obj.value;//值
        var field = obj.field;//字段
        if(commonJS.isEmpty(value)){
            febs.alert.warn('请输入奖励商品数量');
        }
        if(value == 0){
            febs.alert.warn('奖励商品数量必须大于1');
        }
        if(!/^[0-9]+$/.test(value)){
            obj.data.goodsNumber= '';
            obj.update(obj.data);
            tableIns1.reload(1);
            febs.alert.warn('数量必须是正整数');
        }
    })


    /**
     * 开关赋值
     * @param data
     */
    function setSwitchValue(data){
        if(data.field.rewardAmountFlg == 'on'){
            data.field.rewardAmountFlg = '1';
        }else {
            data.field.rewardAmountFlg = '0';
        }
        if(data.field.rewardScoreFlg == 'on'){
            data.field.rewardScoreFlg = '1';
        }else {
            data.field.rewardScoreFlg = '0';
        }
        if(data.field.rewardGoodsFlg == 'on'){
            data.field.rewardGoodsFlg = '1';
            data.field.goodsList = getGoodsTable();
        }else {
            data.field.rewardGoodsFlg = '0';
        }
    }

    /**
     * 获取用户表
     * @returns {*[]}
     */
    function getUserTable(){
        var tableData = table.cache['rewardUserTable'];
        console.log(JSON.stringify(tableData))
        var userList = [];
        tableData.forEach((item, index) => {
            var user = {
                'userId':item.userId,
                'userNo':item.userNo,
                'realName':item.uname,
                'deptId':item.deptId,
                'deptName':item.deptName
            }
            userList.push(user)
        });
        console.log('user'+JSON.stringify(userList))
        return userList;
    }

    /**
     * 校验商品表
     * @returns {boolean}
     */
    function checkGoodsTable(){
        var tableData = table.cache['rewardGoodsTable'];
        if(commonJS.isEmpty(tableData)){
            return false;
        }
        var numberFlg = true
        tableData.forEach((item, index) => {
           if(commonJS.isEmpty(item.goodsNumber) || item.goodsNumber == 0){
               numberFlg = false;
           }
        });
        return numberFlg;
    }

    /**
     * 获取商品表数据
     * @returns {*[]}
     */
    function getGoodsTable(){
        var tableData = table.cache['rewardGoodsTable'];
        console.log('goodtable'+JSON.stringify(tableData))
        var goodsList = [];
        tableData.forEach((item, index) => {
            var good = {
                'goodsName':item.goodsName,
                'goodsNumber':item.goodsNumber,
                'goodsId':item.goodsId
            }
            goodsList.push(good)
        });
        console.log('goods'+JSON.stringify(goodsList))
        return goodsList;
    }

    function getFileData(){
        var imgDatas = $view.find(".fileOne")
        var imgList = [];
        $.each(imgDatas,function (index, item){
            var data = {
                filePath: item.dataset.filepath,
                fileName: item.dataset.filename,
            }
            imgList.push(data);
        })
        return imgList;
    }


});